//
//  NSDate-Extension.swift
//  handleTime
//
//  Created by maker on 2016/11/15.
//  Copyright © 2016年 maker. All rights reserved.
//

import Foundation
extension Date{
   static func getCreatTime(_ orignal : String) -> String {
        //1.创建一个时间格式化对象
        let timeFormat = DateFormatter()
        timeFormat.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        timeFormat.locale = Locale(identifier: "en")
        
        //2.格式化创建的时间
        guard let creatDate = timeFormat.date(from: orignal) else {
            return ""
        }
    
        //3.获取当前的时间
        let nowDate = Date()
        
        //4.获取到时间差
        let interval = Int(nowDate.timeIntervalSince(creatDate))
        
        //5.处理显示时间
        //5.1 显示刚刚
        if interval < 60 {
            return "刚刚"
        }
        //5.2 显示几分钟
        if interval < 60 * 60 {
            return "\(interval/60)分钟前"
        }
        //5.3 显示几个小时前
        if interval < 60 * 60 * 24 {
            return "\(interval/(60 * 60))小时前"
        }
        
        //6.创建日历对象
        let calendar = Calendar.current
        //6.1显示昨天 8:23
        if calendar.isDateInYesterday(creatDate) {
            timeFormat.dateFormat = "昨天 HH:mm"
            return timeFormat.string(from: creatDate)
        }
        
        //6.2 显示一年以内
        let compont = (calendar as NSCalendar).components(.year, from: creatDate, to: nowDate, options: [])

        if compont.year! < 1 {
            timeFormat.dateFormat = "MM-dd HH:mm"
            return timeFormat.string(from: creatDate)
            
        }
        
        //6.3 显示超过一年
        timeFormat.dateFormat = "yyyy-MM-dd HH:mm"
        return timeFormat.string(from: creatDate)
    }
}




